<template>
  <div class="page-container fixed-bottom">
    <el-form ref="form" :model="form" :rules="rules" :disabled="!!id" label-width="110px">
      <div class="form-box">
        <p class="sub-title">基础信息</p>
        <div class="form-item">
          <div :key="1" class="form-flex-item">
            <el-form-item label="优惠券类型：" prop="couponType" required>
              <el-radio-group v-model="form.couponType">
                <el-radio :label="0">满减券</el-radio>
                <el-radio :label="1">折扣券</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div :key="2" class="form-flex-item">
            <el-form-item label="优惠券名称：" prop="couponName">
              <el-input v-model="form.couponName" placeholder="请输入" clearable />
            </el-form-item>
          </div>
          <div :key="3" class="form-flex-item">
            <el-form-item label="优惠券备注：" prop="couponRemark">
              <el-input v-model="form.couponRemark" placeholder="请输入" clearable />
            </el-form-item>
          </div>
          <div v-if="form.couponType === 0" :key="4" class="form-flex-item">
            <el-form-item label="优惠内容：" prop="couponContent">
              <el-radio-group v-model="form.couponMethod">
                <div>
                  <el-radio :label="0">
                    满
                    <el-input v-model="form.fullNum" v-money class="min-input" placeholder="请输入" clearable />
                    <el-select v-model="form.couponUnit" class="min-select" clearable>
                      <el-option :value="'0'" label="元" />
                      <el-option :value="'1'" label="件" />
                    </el-select>
                    减
                    <el-input v-model="form.reduceAmount" v-money class="min-input" placeholder="请输入金额" clearable />
                  </el-radio>
                </div>
                <div class="coupon-item">
                  <el-radio :label="1">
                    无门槛 减
                    <el-input v-model="form.reAmount" v-money class="min-input" placeholder="请输入金额" clearable />
                  </el-radio>
                </div>
              </el-radio-group>
            </el-form-item>
          </div>
          <div v-if="form.couponType === 1" :key="5" class="form-flex-item">
            <el-form-item label="优惠内容：" prop="couponContent">
              <el-radio-group v-model="form.couponMethod">
                <div>
                  <el-radio :label="0">
                    满
                    <el-input v-model="form.fullNum" v-money class="min-input" placeholder="请输入" clearable />
                    <el-select v-model="form.couponUnit" class="min-select" clearable>
                      <el-option :value="'0'" label="元" />
                      <el-option :value="'1'" label="件" />
                    </el-select>
                    打
                    <el-input v-model="form.reduceAmount" v-money class="min-input" placeholder="请输入折扣" clearable />
                    折
                  </el-radio>
                </div>
                <div class="coupon-item">
                  <el-radio :label="1">
                    无门槛 打
                    <el-input v-model="form.reAmount" v-money class="min-input" placeholder="请输入折扣" clearable />
                    折
                  </el-radio>
                </div>
              </el-radio-group>
            </el-form-item>
          </div>
          <div v-if="form.couponType === 1" :key="6" class="form-flex-item">
            <el-form-item label="优惠上限：" prop="maxPreferential">
              最多优惠
              <el-input v-model="form.maxPreferential" v-money class="min-input" placeholder="请输入金额" clearable />
            </el-form-item>
          </div>
          <div :key="7" class="form-flex-item">
            <el-form-item label="可使用时间：" prop="userTimeType">
              <el-radio-group v-model="form.userTimeType">
                <div>
                  <el-radio :label="0">
                    <el-date-picker
                      v-model="form.effectiveTime"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      type="datetimerange"
                      range-separator="至"
                      start-placeholder="生效时间"
                      end-placeholder="时效时间"
                      :default-time="['00:00:00', '23:59:59']"
                    />
                  </el-radio>
                </div>
                <div class="coupon-item">
                  <el-radio :label="1">
                    领券后立即生效，有效期
                    <el-input v-model="form.effective" v-int class="min-input" placeholder="请输入天数" clearable />
                    天
                  </el-radio>
                </div>
              </el-radio-group>
            </el-form-item>
          </div>
          <div :key="8" class="form-flex-item">
            <el-form-item label="发放周期：" prop="publishCycle" required>
              <el-radio-group v-model="form.publishCycle">
                <el-radio :label="0">一次性发放</el-radio>
                <el-radio :label="1">周期性</el-radio>
                <el-radio :label="2">自定义</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div v-if="form.publishCycle === 0" :key="9" class="form-flex-item">
            <el-form-item label="发放量：" prop="distributionNum">
              <el-input v-model="form.distributionNum" placeholder="请输入数量" clearable />
            </el-form-item>
          </div>
          <div v-if="form.publishCycle === 1" :key="10" class="form-flex-item">
            <el-form-item label="发放量：" prop="cycleGrant">
              <el-date-picker
                v-model="form.cycleGrant.grantDateRange"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
              />
              期间，每天发放
              <el-input v-model="form.cycleGrant.distributionNum" class="min-input" placeholder="请输入数量" clearable />
              张
            </el-form-item>
          </div>
          <div v-if="form.publishCycle === 2" :key="11" class="form-flex-item">
            <el-form-item label="发放量：">
              <div v-for="(item ,index) in form.customGrant" :key="index" :class="index !==0 ?'coupon-item':''">
                <el-date-picker
                  v-model="item.dateRange"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :default-time="['00:00:00', '23:59:59']"
                />
                期间，每天发放
                <el-input v-model="item.distributionNum" class="min-input" placeholder="请输入数量" clearable />
                张，抢券时间：
                <el-date-picker
                  v-model="item.date"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  class="min-date"
                  type="datetime"
                  placeholder="请选择"
                />
                <el-button v-if="index !==0" icon="el-icon-minus" v class="delete-icon" @click="deleteItem(index)" />
              </div>
              <p><el-button icon="el-icon-plus" class="add-icon" @click="addItem" /></p>
            </el-form-item>
          </div>
          <div v-if="form.publishCycle === 0" :key="12" class="form-flex-item">
            <el-form-item label="抢券时间：" prop="grabTime">
              <el-date-picker
                v-model="form.grabTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
              />
            </el-form-item>
          </div>
          <div v-if="form.publishCycle === 1" :key="13" class="form-flex-item">
            <el-form-item label="抢券时间：" prop="cycleGrantTime">
              <el-radio-group v-model="form.cycleGrant.grabTimeType">
                <p>
                  <el-radio :label="0">
                    不重复，自
                    <el-date-picker
                      v-model="form.cycleGrant.grabDate"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      class="min-date"
                      type="datetime"
                      placeholder="请选择"
                    />
                    开抢
                  </el-radio>
                </p>
                <p class="coupon-item">
                  <el-radio :label="1">
                    重复，每日
                    <el-time-picker
                      v-model="form.cycleGrant.grabTime"
                      value-format="HH:mm:ss"
                      class="min-date"
                      placeholder="选择时间"
                    />
                    开抢
                  </el-radio>
                </p>
                <p class="coupon-item">
                  <el-radio :label="2">
                    每日
                    <el-time-picker
                      v-model="form.cycleGrant.grabTimeRange"
                      value-format="HH:mm:ss"
                      class="min-date"
                      is-range
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                    />
                    开抢
                  </el-radio>
                </p>
              </el-radio-group>
            </el-form-item>
          </div>
          <div :key="14" class="form-flex-item">
            <el-form-item label="适用门店：" prop="siteIds">
              <el-select v-model="form.siteIds" multiple clearable>
                <el-option v-for="item in siteList" :key="item.id" :value="String(item.id)" :label="item.name" />
              </el-select>
            </el-form-item>
          </div>
          <div :key="15" class="form-flex-item">
            <el-form-item label="可选范围：" prop="couponRange" required>
              <el-radio-group v-model="form.couponRange">
                <el-radio :label="0">全品类</el-radio>
                <el-radio :label="1">指定品类</el-radio>
                <el-radio :label="2">指定商品</el-radio>
                <el-radio :label="3">套票</el-radio>
                <el-radio :label="4">油品</el-radio>
                <el-radio :label="5">自助洗车</el-radio>
                <el-radio :label="6">课程</el-radio>
              </el-radio-group>
              <div class="coupon-item">
                <el-button v-if="form.couponRange === 1" type="primary" @click="addContent(1)">选择行业/类目</el-button>
                <el-button v-if="form.couponRange === 2" type="primary" @click="addContent(2)">选择商品</el-button>
                <el-button v-if="form.couponRange === 3" type="primary" @click="addContent(3)">选择套票</el-button>
                <el-button v-if="form.couponRange === 4" type="primary" @click="addContent(4)">选择油品</el-button>
                <el-button v-if="form.couponRange === 5" type="primary" @click="addContent(5)">选择洗车设备</el-button>
                <el-button v-if="form.couponRange === 6" type="primary" @click="addContent(6)">选择课程</el-button>
              </div>
            </el-form-item>
          </div>
        </div>
      </div>
      <div class="form-box">
        <p class="sub-title">发放和使用规则</p>
        <div class="form-item">
          <div :key="16" class="form-flex-item">
            <el-form-item label="发放渠道：" prop="couponChannel" required>
              <el-radio-group v-model="form.couponChannel">
                <el-radio :label="0">领券中心</el-radio>
                <el-radio :label="1">定向发放</el-radio>
              </el-radio-group>
              <p v-if="form.couponChannel === 1" class="coupon-item">
                <el-button type="primary">添加发放用户</el-button>
              </p>
            </el-form-item>
          </div>
          <div :key="17" class="form-flex-item">
            <el-form-item label="领取次数：" prop="couponLimit" required>
              <el-radio-group v-model="form.couponLimit">
                <el-radio :label="0">每人领取次数不限</el-radio>
                <el-radio :label="1">
                  每人最多可领取
                  <el-input v-model="form.limitNum" class="min-input" placeholder="请输入次数" clearable />
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div :key="18" class="form-flex-item">
            <el-form-item label="发放配置：" prop="publishConfig" required>
              <el-radio-group v-model="form.publishConfig">
                <p class="coupon-item">
                  <el-radio :label="0">立即发行</el-radio>
                </p>
                <p class="coupon-item">
                  <el-radio :label="1">
                    定时发行
                    <el-date-picker
                      v-model="form.publishTime"
                      class="min-date"
                      type="datetime"
                      placeholder="请选择"
                    />
                  </el-radio>
                </p>
                <p class="coupon-item">
                  <el-radio :label="2">稍后发行</el-radio>
                </p>
              </el-radio-group>
            </el-form-item>
          </div>
          <div :key="19" class="form-flex-item">
            <el-form-item label="叠加设置：" prop="exclusion" required>
              <el-radio-group v-model="form.exclusion">
                <el-radio :label="0">互斥</el-radio>
                <el-radio :label="1">不互斥</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div :key="20" class="form-flex-item">
            <el-form-item label="优惠券说明：" prop="couponDesc">
              <el-input v-model="form.couponDesc" type="textarea" rows="5" placeholder="请输入" clearable />
            </el-form-item>
          </div>
        </div>
      </div>
    </el-form>
    <div v-if="!id" class="bottom-handle-box">
      <el-button @click="goBack">返回</el-button>
      <el-button type="primary" :loading="loading" @click="confirmHandle">保存</el-button>
    </div>
    <AddContent
      v-if="showAddContent"
      :type="addType"
      :site-ids="form.siteIds"
      @close="closeHandle"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getAllSiteList } from '@/api/enter'
import { creatCoupon, getCouponDetail } from '@/api/coupon'
import AddContent from './AddContent.vue'

export default {
  name: 'CouponDetail',
  components: {
    AddContent
  },
  data() {
    const validateCycleGrant = (rule, value, callback) => {
      const { grantDateRange, distributionNum } = this.form.cycleGrant
      if (grantDateRange && distributionNum) {
        callback()
      } else {
        callback(new Error('请输入发放量'))
      }
    }
    const validateCycleGrantTime = (rule, value, callback) => {
      const { grabTimeType, grabDate, grabTime, grabTimeRange } = this.form.cycleGrant
      if (grabTimeType === 0 && grabDate) {
        callback()
      } else if (grabTimeType === 1 && grabTime) {
        callback()
      } else if (grabTimeType === 2 && grabTimeRange) {
        callback()
      } else {
        callback(new Error('请输入发放量'))
      }
    }
    const validateCouponContent = (rule, value, callback) => {
      const { couponMethod, fullNum, couponUnit, reduceAmount, reAmount } = this.form
      if (couponMethod === 0 && fullNum && couponUnit && reduceAmount) {
        callback()
      } else if (couponMethod === 1 && reAmount) {
        callback()
      } else {
        callback(new Error('请输入优惠券内容'))
      }
    }
    const validateUseTimeType = (rule, value, callback) => {
      const { userTimeType, effectiveTime, effective } = this.form
      if (userTimeType === 0 && effectiveTime.length) {
        callback()
      } else if (userTimeType === 1 && effective) {
        callback()
      } else {
        callback(new Error('请输入优惠券可使用时间'))
      }
    }

    return {
      id: '',
      siteList: [],
      form: {
        couponType: 0,
        couponName: '',
        couponRemark: '',
        couponMethod: 0,
        fullNum: '',
        couponUnit: '',
        reduceAmount: '',
        reAmount: '',
        maxPreferential: '',
        userTimeType: 0,
        effectiveTime: [],
        effective: '',
        publishCycle: 0,
        distributionNum: '',
        grabTime: [],
        cycleGrant: {
          grantDateRange: '',
          distributionNum: '',
          grabTimeType: 0,
          grabDate: '',
          grabTime: '',
          grabTimeRange: ''
        },
        customGrant: [
          {
            dateRange: '',
            distributionNum: '',
            date: ''
          }
        ],
        siteIds: [],
        couponRange: 0,
        couponChannel: 0,
        couponLimit: 0,
        limitNum: '',
        publishConfig: 0,
        publishTime: '',
        exclusion: 0,
        couponDesc: ''
      },
      rules: {
        couponName: [{ required: true, message: '请输入优惠券名称', trigger: ['blur'] }],
        couponRemark: [{ required: true, message: '请输入优惠券备注', trigger: ['blur'] }],
        couponContent: [{ required: true, validator: validateCouponContent, trigger: ['blur', 'change'] }],
        maxPreferential: [{ required: true, message: '请输入优惠上限', trigger: ['blur'] }],
        cycleGrant: [{ required: true, validator: validateCycleGrant, trigger: ['blur', 'change'] }],
        cycleGrantTime: [{ required: true, validator: validateCycleGrantTime, trigger: ['blur', 'change'] }],
        userTimeType: [{ required: true, validator: validateUseTimeType, trigger: ['blur', 'change'] }],
        distributionNum: [{ required: true, message: '请输入发放量', trigger: ['blur'] }],
        grabTime: [{ required: true, message: '请选择抢券时间', trigger: ['blur'] }],
        siteIds: [{ required: true, message: '请选择适用门店', trigger: ['blur', 'change'] }],
        couponDesc: [{ required: true, message: '请输入优惠券说明', trigger: ['blur'] }]
      },
      loading: false,
      showAddContent: false,
      addType: null
    }
  },
  computed: {
    ...mapGetters([
      'currentSite'
    ])
  },

  created() {
    this.id = this.$route.query.id
    this.getAllSiteList()
    if (this.id) {
      this.getCouponDetail()
    }
  },

  methods: {

    // 获取所有站点
    getAllSiteList() {
      getAllSiteList().then(res => {
        this.siteList = res || []
      }).catch(() => {})
    },

    // 获取优惠券详情
    getCouponDetail() {
      const data = {
        id: this.id
      }
      getCouponDetail(data).then(res => {
        const {
          couponType,
          couponName,
          couponRemark,
          couponMethod,
          fullNum,
          couponUnit,
          reduceAmount,
          reAmount,
          maxPreferential,
          userTimeType,
          startDate,
          endDate,
          effective,
          publishCycle,
          distributionNum,
          grabStartTime,
          grabEndTime,
          couponCycleBaseVOS = [],
          siteIds,
          couponRange,
          couponChannel,
          couponLimit,
          limitNum,
          publishConfig,
          publishTime,
          exclusion,
          couponDesc
        } = res
        let customGrant = []
        const cycleGrant = {
          grantDateRange: '',
          distributionNum: '',
          grabTimeType: 0,
          grabDate: '',
          grabTime: '',
          grabTimeRange: ''
        }
        if (publishCycle === 1) {
          const { cycleType, startDate, startTime, endDate, endTime, distributionNum, grabStartDate, grabStartTime, grabEndTime } = couponCycleBaseVOS[0]
          cycleGrant.grabTimeType = cycleType
          cycleGrant.grantDateRange = [`${startDate} ${startTime}`, `${endDate} ${endTime}`]
          cycleGrant.distributionNum = distributionNum
          if (cycleType === 0) {
            cycleGrant.grabDate = `${grabStartDate} ${grabStartTime}`
          } else if (cycleType === 1) {
            cycleGrant.grabTime = grabStartTime
          } else if (cycleType === 2) {
            cycleGrant.grabTimeRange = [grabStartTime, grabEndTime]
          }
        } else if (publishCycle === 2) {
          customGrant = couponCycleBaseVOS.map(item => {
            const startDateTime = `${item.startDate} ${item.startTime}`
            const endDateTime = `${item.endDate} ${item.endTime}`
            const date = `${item.grabStartDate} ${item.grabEndTime}`
            return {
              dateRange: [startDateTime, endDateTime],
              distributionNum: item.distributionNum,
              date
            }
          })
        }
        this.form = {
          couponType,
          couponName,
          couponRemark,
          couponMethod,
          fullNum,
          couponUnit: couponUnit.toString(),
          reduceAmount,
          reAmount,
          maxPreferential,
          userTimeType,
          effectiveTime: [startDate, endDate],
          effective,
          publishCycle,
          distributionNum,
          grabTime: [grabStartTime, grabEndTime],
          cycleGrant,
          customGrant,
          siteIds: siteIds ? siteIds.split(',') : [],
          couponRange,
          couponChannel,
          couponLimit,
          limitNum,
          publishConfig,
          publishTime,
          exclusion,
          couponDesc
        }
      }).catch(() => {})
    },

    // 新增
    addItem() {
      this.form.customGrant.push({
        dateRange: '',
        distributionNum: '',
        date: ''
      })
    },

    // 删除
    deleteItem(index) {
      this.form.customGrant.splice(index, 1)
    },

    // 返回
    goBack() {
      this.$router.back()
    },

    // 新增可用范围
    addContent(index) {
      this.showAddContent = true
      this.addType = index
    },

    // 关闭
    closeHandle() {
      this.showAddContent = false
      this.addType = ''
    },

    // 保存
    confirmHandle() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const {
            couponType,
            couponName,
            couponRemark,
            couponMethod,
            fullNum,
            couponUnit,
            reduceAmount,
            reAmount,
            maxPreferential,
            userTimeType,
            effectiveTime,
            effective,
            publishCycle,
            distributionNum,
            cycleGrant,
            customGrant,
            grabTime,
            siteIds,
            couponRange,
            couponChannel,
            couponLimit,
            limitNum,
            publishConfig,
            publishTime,
            exclusion,
            couponDesc
          } = this.form
          let customGrantList = []
          let cycleGrantList = []
          if (publishCycle === 1) {
            const [startDateTime, endDateTime] = cycleGrant.grantDateRange
            const [startDate, startTime] = startDateTime.split(' ')
            const [endDate, endTime] = endDateTime.split(' ')
            const temp = {
              cycleType: cycleGrant.grabTimeType,
              distributionNum: cycleGrant.distributionNum,
              startDate,
              endDate,
              startTime,
              endTime
            }
            if (cycleGrant.grabTimeType === 0) {
              const [grabStartDate, grabStartTime] = cycleGrant.grabDate.split(' ')
              Object.assign(temp, { grabStartDate, grabStartTime })
            } else if (cycleGrant.grabTimeType === 1) {
              const grabStartTime = cycleGrant.grabTime
              Object.assign(temp, { grabStartTime })
            } else if (cycleGrant.grabTimeType === 2) {
              const [grabStartTime, grabEndTime] = cycleGrant.grabTimeRange
              Object.assign(temp, { grabStartTime, grabEndTime })
            }
            cycleGrantList = [temp]
          } else if (publishCycle === 2) {
            customGrantList = customGrant.map(item => {
              const [startDateTime, endDateTime] = item.dateRange
              const [startDate, startTime] = startDateTime.split(' ')
              const [endDate, endTime] = endDateTime.split(' ')
              const [grabStartDate, grabEndTime] = item.date.split(' ')
              return {
                startDate,
                startTime,
                endDate,
                endTime,
                grabStartDate,
                grabEndTime,
                distributionNum: item.distributionNum
              }
            })
          }
          const data = {
            couponType,
            couponName,
            couponRemark,
            couponMethod,
            fullNum: couponMethod === 0 ? fullNum : undefined,
            couponUnit: couponMethod === 0 ? couponUnit : undefined,
            reduceAmount: couponMethod === 0 ? reduceAmount : undefined,
            reAmount: couponMethod === 1 ? reAmount : undefined,
            maxPreferential: couponType === 1 ? maxPreferential : undefined,
            userTimeType,
            startDate: userTimeType === 0 ? effectiveTime[0] : undefined,
            endDate: userTimeType === 0 ? effectiveTime[1] : undefined,
            effective: userTimeType === 1 ? effective : undefined,
            publishCycle,
            distributionNum: publishCycle === 0 ? distributionNum : undefined,
            couponCycleBaseVOS: publishCycle === 2 ? customGrantList : (publishCycle === 1 ? cycleGrantList : undefined),
            grabStartTime: publishCycle === 0 ? grabTime[0] : undefined,
            grabEndTime: publishCycle === 0 ? grabTime[1] : undefined,
            siteIds: siteIds.join(','),
            couponRange,
            couponChannel,
            couponLimit,
            limitNum: couponLimit === 1 ? limitNum : undefined,
            publishConfig,
            publishTime: publishConfig === 1 ? publishTime : undefined,
            exclusion,
            couponDesc,
            siteId: this.currentSite.id
          }
          console.log(data)
          this.loading = true
          creatCoupon(data).then(res => {
            this.loading = false
            this.$message.success('新增成功')
            this.$router.back()
          }).catch(() => {
            this.loading = false
          })
        }
      })
    }

  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables";
.form-box{
  padding: 20px 30px;
  .sub-title{
    font-weight: 700;
    font-size: 18px;
    line-height: 20px;
    color: #333;
    padding-left: 20px;
    border-left: 4px solid $primary;
  }

  .form-item {
    margin-top: 20px;
  }

  .form-flex-item{
    display: flex;
    //width: 900px;
  }

  .coupon-item{
    margin-top: 10px;
  }

  .el-input, .el-select, .el-textarea{
    width: 400px;
  }

  .el-date-editor{
    width: 400px;
  }

  .min-date{
    width: 200px;
  }

  .min-input{
    width: 140px;
    padding: 0 5px;
  }
  .min-select{
    width: 140px;
    padding: 0 5px;
  }

  .add-icon{
    margin-top: 20px;
  }

  .delete-icon{
    margin-left: 20px;
  }

}
</style>
